package com.qiandw.service.impl;

import com.qiandw.activiti.LeaveService;
import com.qiandw.dao.LeaveBillDao;
import com.qiandw.entity.LeaveBill;
import com.qiandw.service.LeaveBillService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 请假单实现类
 */
@Service("leaveBillService")
public class LeaveBillServiceImpl implements LeaveBillService {
    @Autowired
    @Qualifier("leaveBillDao")
    private LeaveBillDao leaveBillDao;
    @Resource
    private LeaveService leaveService;
    @Resource
    private RuntimeService runtimeService;

    /**
     * 新增请假单
     *
     * @param leaveBill 请假单
     * @return
     */
    @Override
    public LeaveBill add(LeaveBill leaveBill) {
        leaveBillDao.save(leaveBill);
        //启动流程
        leaveService.startProcess(leaveBill.getId());
        //保存请假单
        return leaveBill;
    }

    /**
     * 查询代办
     *
     * @param userId userId
     * @return
     */
    @Override
    public List<LeaveBill> findByUserId(String userId) {
        List<Task> taskList = leaveService.findTaskByUserId(userId);
        List<LeaveBill> result = new ArrayList<LeaveBill>();
        for (Task task : taskList) {
            //更具流程实例id查询流程实例
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            //从流程实例中查询业务id
            String businessId = processInstance.getBusinessKey();
            LeaveBill leaveBill = leaveBillDao.findOne(businessId);
            leaveBill.setTaskId(task.getId());
            result.add(leaveBill);
        }
        return result;
    }

    /**
     * 完成任务
     *
     * @param taskId 任务id(表示审批那个任务)
     * @param userId 谁来审批
     * @param audit  审批意见 pass,reject
     */
    @Override
    public void completeTaskByUser(String taskId, String userId, String audit) {
        leaveService.completeTaskByUser(taskId, userId, audit);
    }
}
